package com.yihu.wlyy.web.doctor.health;

import java.util.*;

import com.yihu.wlyy.health.entity.DevicePatientHealthIndex;
import com.yihu.wlyy.util.SystemConf;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yihu.wlyy.entity.patient.PatientHealthStandard;
import com.yihu.wlyy.service.app.health.PatientHealthIndexService;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.web.BaseController;

@Controller
@RequestMapping(value = "/doctor/health_index")
@Api(description = "患者指标接口--医生端")
public class DoctorHealthController extends BaseController {

	@Autowired
	private PatientHealthIndexService healthIndexService;

	/**
	 * 患者最近填写的健康指标
	 * @param patient 患者标识
	 * @return
	 */
	@RequestMapping(value = "recent")
	@ResponseBody
	public String recent(String patient) {
		try {
			JSONArray array = healthIndexService.findRecentByPatient(patient);
			if (array != null) {
				return write(200, "查询成功", "list", array);
			} else {
				return error(-1, "查询失败");
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败");
		}
	}

	/**
	 * 根据患者标志获取健康指标
	 * @param patient 患者标识
	 * @param type 健康指标类型（1血糖，2血压，3体重，4腰围）
	 * @return 操作结果
	 */
	@RequestMapping(value = "chart",method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation("根据患者标志获取健康指标(图表)")
	public String getHealthIndexChartByPatient(@ApiParam(name="patient",value="指标类型",defaultValue = "P20160902002")
												   @RequestParam(value="patient",required = true) String patient,
											   @ApiParam(name="type",value="指标类型",defaultValue = "1")
											   @RequestParam(value="type",required = true) int type,
											   @ApiParam(name="begin",value="开始时间",defaultValue = "2016-08-23 00:00:00")
											   @RequestParam(value="begin",required = true) String begin,
											   @ApiParam(name="end",value="结束时间",defaultValue = "2016-09-23 00:00:00")
												   @RequestParam(value="end",required = true) String end) {
		try {
			Iterable<DevicePatientHealthIndex> list = healthIndexService.findChartByPatien(patient, type, begin, end);
			if (list == null) {
				return success("查询成功!");
			}
			JSONArray jsonArray = new JSONArray();
			for (DevicePatientHealthIndex model : list) {
				JSONObject modelJson = new JSONObject();
				modelJson.put("patient", model.getUser());
				modelJson.put("value1", model.getValue1());
				modelJson.put("value2", model.getValue2());
				modelJson.put("value3", model.getValue3());
				modelJson.put("value4", model.getValue4());
				modelJson.put("value5", model.getValue5());
				modelJson.put("value6", model.getValue6());
				modelJson.put("value7", model.getValue7());
				modelJson.put("type", model.getType());
				modelJson.put("date", DateUtil.dateToStr(model.getRecordDate(), DateUtil.YYYY_MM_DD));
				modelJson.put("czrq", DateUtil.dateToStr(model.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
				jsonArray.put(modelJson);
			}
			return write(200, "查询成功", "list", jsonArray);
		} catch (Exception ex) {
			error(ex);
			return invalidUserException(ex, -1, "查询失败！");
		}
	}

	/**
	 * 根据患者标志获取健康指标
	 * @param patient 患者指标
	 * @param type 健康指标类型（1血糖，2血压，3体重，4腰围）
	 * @return 操作结果
	 */
	@RequestMapping(value = "list",method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation("根据患者标志获取健康指标")
	public String getHealthIndexByPatient(@ApiParam(name="patient",value="患者代码",defaultValue = "P20160901001")
											  @RequestParam(value="patient",required = true) String patient,
										  @ApiParam(name="type",value="指标类型",defaultValue = "1")
										  @RequestParam(value="type",required = true) int type,
										  @ApiParam(name="begin",value="开始时间",defaultValue = "2016-07-23 00:00:00")
											  @RequestParam(value="begin",required = true) String begin,
										  @ApiParam(name="end",value="开始时间",defaultValue = "2016-08-23 00:00:00")
											  @RequestParam(value="end",required = true) String end,
										  @ApiParam(name="page",value="第几页",defaultValue = "1")
											  @RequestParam(value="page",required = true) int page,
										  @ApiParam(name="pagesize",value="每页几行",defaultValue = "10")
											  @RequestParam(value="pagesize",required = true) int pagesize) {
		try {
			List<DevicePatientHealthIndex> list = healthIndexService.findIndexByPatient(patient, type, begin,end,page, pagesize);

			JSONArray jsonArray = new JSONArray();
			for (DevicePatientHealthIndex model : list) {
				JSONObject modelJson = new JSONObject();
				modelJson.put("id", model.getId());
				modelJson.put("patient", model.getUser());
				modelJson.put("value1", model.getValue1());
				modelJson.put("value2", model.getValue2());
				modelJson.put("value3", model.getValue3());
				modelJson.put("value4", model.getValue4());
				modelJson.put("value5", model.getValue5());
				modelJson.put("value6", model.getValue6());
				modelJson.put("value7", model.getValue7());
				modelJson.put("type", model.getType());
				modelJson.put("date", DateUtil.dateToStrShort(model.getRecordDate()));
				modelJson.put("sortDate", DateUtil.dateToStrLong(model.getSortDate()));
				modelJson.put("czrq", DateUtil.dateToStr(model.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
				jsonArray.put(modelJson);
			}

			return write(200, "查询成功", "list", jsonArray);
		} catch (Exception ex) {
			error(ex);
			return invalidUserException(ex, -1, "查询失败！");
		}
	}

	/**
	 * 患者健康指标预警值查询
	 * @param patient 患者标识
	 * @return
	 */
	@RequestMapping(value = "standard")
	@ResponseBody
	public String standard(String patient) {
		try {
			JSONArray standardArray = new JSONArray();
			JSONArray userArray = new JSONArray();
			Iterable<PatientHealthStandard> iterable = healthIndexService.findStandardByPatient(patient);
			Iterator<PatientHealthStandard> iterator = null;
			if (iterable != null) {
				iterator = iterable.iterator();
			}
			// 预警值未设置，返回默认值
			StringBuffer sb = new StringBuffer();
			sb.append("[");
			// 默认血糖（餐前，餐后二小时）

			sb.append("{min_value_1:"+ SystemConf.HEALTH_STANDARD_ST_MIN_BEFORE +", max_value_1: "+ SystemConf.HEALTH_STANDARD_ST_MAX_BEFORE +", " +
					"min_value_2:"+ SystemConf.HEALTH_STANDARD_ST_MIN_AFTER +", max_value_2:"+ SystemConf.HEALTH_STANDARD_ST_MAX_AFTER +", type:1},");
			// 默认血压（收缩压，舒张压）
			sb.append("{min_value_1:"+ SystemConf.HEALTH_STANDARD_SSY_MIN +", max_value_1:"+ SystemConf.HEALTH_STANDARD_SSY_MAX +", " +
					"min_value_2:"+ SystemConf.HEALTH_STANDARD_SZY_MIN +", max_value_2:"+ SystemConf.HEALTH_STANDARD_SZY_MAX +", type:2}");
			sb.append("]");
			standardArray = new JSONArray(sb.toString());
			if (iterator != null) {
				while (iterator.hasNext()) {
					PatientHealthStandard phs = iterator.next();
					if (phs == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					// 最低安全值(血糖餐前\收缩压\体重\腰围)
					json.put("min_value_1", phs.getMinValue1());
					// 最高安全值(血糖餐前\收缩压\体重\腰围)
					json.put("max_value_1", phs.getMaxValue1());
					// 最低安全值(血糖餐后\舒张压)
					json.put("min_value_2", phs.getMinValue2());
					// 最高安全值(血糖餐后\舒张压)
					json.put("max_value_2", phs.getMaxValue2());
					// 健康指标类型：1血糖，2血压，3体重，4腰围
					json.put("type", phs.getType());
					userArray.put(json);
				}
			}
			JSONObject json = new JSONObject();
			json.put("standard", standardArray);
			json.put("custom", userArray);
			return write(200, "查询成功", "data", json);
		} catch (Exception e) {
			error(e);
			return invalidUserException(e, -1, "查询失败！");
		}
	}

	/**
	 * 保存患者健康指标预警值
	 * @param patient 患者标识
	 * @param json 预警值
	 * @return
	 */
	@RequestMapping(value = "standard_save")
	@ResponseBody
	public String standardSave(String patient, String json) {
		try {
			JSONArray array = new JSONArray(json);
			if (StringUtils.isEmpty(patient) || array == null || array.length() == 0) {
				return error(-1, "保存失败！");
			}
			// 生成数据对象
			List<PatientHealthStandard> list = new ArrayList<PatientHealthStandard>();
			for (int i = 0; i < array.length(); i++) {
				JSONObject obj = array.getJSONObject(i);
				if (obj == null) {
					continue;
				}
				PatientHealthStandard standard = new PatientHealthStandard();
				standard.setDoctor(getUID());
				standard.setMaxValue1(obj.has("max_value1") ? NumberUtils.toDouble(obj.getString("max_value1"), 0) : 0);
				standard.setMaxValue2(obj.has("max_value2") ? NumberUtils.toDouble(obj.getString("max_value2"), 0) : 0);
				standard.setMinValue1(obj.has("min_value1") ? NumberUtils.toDouble(obj.getString("min_value1"), 0) : 0);
				standard.setMinValue2(obj.has("min_value2") ? NumberUtils.toDouble(obj.getString("min_value2"), 0) : 0);
				standard.setType(obj.getInt("type"));
				standard.setPatient(patient);
				standard.setCzrq(new Date());
				list.add(standard);
			}
			if (list.size() == 0) {
				return error(-1, "保存失败！");
			}
			// 保存数据库
			Iterable<PatientHealthStandard> iterable = healthIndexService.saveStandard(list, patient);
			if (iterable == null || iterable.iterator() == null || !iterable.iterator().hasNext()) {
				return error(-1, "保存失败！");
			}
			return write(200, "保存成功");
		} catch (Exception e) {
			error(e);
			return invalidUserException(e, -1, "保存失败！");
		}
	}


	/**
	 * 根据患者标志获取健康指标
	 * @param patient 患者指标
	 * @return 操作结果
	 */
	@RequestMapping(value = "last",method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation("患者最新健康指标信息")
	public String getHealthIndexByPatient(@ApiParam(name="patient",value="患者代码",defaultValue = "")
										   @RequestParam(value="patient",required = true) String patient) {
		try {
			Map<String,Object> map = new HashMap<>();
			DevicePatientHealthIndex xt = healthIndexService.findLastByPatien(patient,1);
			if(xt!=null)
			{
				map.put("xt",xt);
			}
			DevicePatientHealthIndex xy = healthIndexService.findLastByPatien(patient,2);
			if(xy!=null)
			{
				map.put("xy",xy);
			}

			return write(200, "查询成功", "data", map);
		} catch (Exception ex) {
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}

}
